package com.atguigu.gmall.ums.service.impl;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.core.bean.PageVo;
import com.atguigu.core.bean.Query;
import com.atguigu.core.bean.QueryCondition;

import com.atguigu.gmall.ums.dao.MemberDao;
import com.atguigu.gmall.ums.entity.MemberEntity;
import com.atguigu.gmall.ums.service.MemberService;

@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Override
    public PageVo queryPage(QueryCondition params) {
        IPage<MemberEntity> page =
            this.page(new Query<MemberEntity>().getPage(params), new QueryWrapper<MemberEntity>());

        return new PageVo(page);
    }

    @Override
    public boolean checkData(String data, Integer type) {
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        switch (type) {
            case 1:
                wrapper.eq("username", data);
                break;
            case 2:
                wrapper.eq("mobile", data);
                break;
            case 3:
                wrapper.eq("email", data);
                break;
            default:
                return false;
        }
        int count = this.count(wrapper);
        return count == 0;
    }

    @Override
    public Boolean register(MemberEntity memberEntity, String code) {
        // 生成盐
        String salt = StringUtils.replace(UUID.randomUUID().toString(), "-", "");
        memberEntity.setSalt(salt);
        // 对密码进行加密
        String newPassword = DigestUtils.md5Hex(salt + memberEntity.getPassword());
        memberEntity.setPassword(newPassword);
        // 创建时间
        memberEntity.setCreateTime(new Date());
        boolean flag = this.save(memberEntity);
        return flag;
    }

    @Override
    public MemberEntity queryUser(String username, String password) {
        // 查询用户
        MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>().eq("username", username));
        // 检验密码
        if (!memberEntity.getPassword().equals(DigestUtils.md5Hex(memberEntity.getSalt() + password))) {
            return null;
        }
        return memberEntity;
    }

}